<!--
 * @Description: 
 * @Author: william
 * @Date: 2025-08-11 20:07:14
 * @LastEditors: william
 * @LastEditTime: 2025-08-13 15:16:24
-->
<template>
  <div class="content-container">
    <div class="base-table-container">
      <div class="chat-items" ref="refChatItems">
        <div v-if="msgLoading" class="no-msg">正在加载历史消息~~</div>
        <div v-else-if="!msgList.length" class="no-msg">暂无更多消息~~</div>
        <TextMsgView
          v-for="item in msgList"
          :row="item"
          :key="item.id"
          type="system"
          @menu="hanldeContextMenu(item)"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import TextMsgView from '@/views/message/chatMessage/component/TextMsgView.vue'

const userStore = useUserStore()
const { userInfo, eventSource } = storeToRefs(userStore)
// 聊天参数
const refChatItems = ref(null)
const msgLoading = ref(false)
const msgList = ref([])
// 取消请求参数
const controller = ref(null)

watch(
  () => msgList.value.length,
  (nv, ov) => {
    if (nv !== ov) {
      nextTick(() => {
        scrollToBottom()
      })
    }
  },
  {
    deep: true
  }
)

onMounted(() => {
  controller.value = new AbortController()
  getChatMsg()
  eventSource.value.on('chat-system', chatMsgDeal)
})

onBeforeUnmount(() => {
  // 如果存在未完成的请求，则取消它
  if (controller.value) {
    controller.value.abort()
    console.log('controller.value-取消未完成的请求!')
  }
  eventSource.value.off('chat-system', chatMsgDeal)
})

const chatMsgDeal = event => {
  // console.log('on chat-system', event)
  const data = JSON.parse(event.data).data
  console.log('chat-system-data', data)
  if (data.toId !== userInfo.value.tenantId) return
  const foundItem = msgList.value.find(item => {
    return String(item.id) === String(data.id)
  })
  if (foundItem) {
    // 如果找到相同id的项，合并数据
    Object.assign(foundItem, data)
  } else {
    msgList.value.push(data)
  }
}

const getChatMsg = () => {
  msgLoading.value = true
  msgList.value = []
  g_api.sysMsg
    .apiMsgList(
      {
        userId: userInfo.value.userId,
        toId: userInfo.value.tenantId,
        source: 'system',
        pageNum: 1,
        pageSize: 300
      },
      {},
      {
        signal: controller.value.signal
      }
    )
    .then(({ code, data }) => {
      if (code === '200' && data) {
        msgList.value = data.items
      }
    })
    .finally(() => {
      msgLoading.value = false
    })
}

const scrollToBottom = () => {
  setTimeout(() => {
    if (!refChatItems.value) return
    refChatItems.value.scrollTop =
      refChatItems.value.scrollHeight - refChatItems.value.offsetHeight
  })
}

const hanldeContextMenu = row => {
  console.log('hanldeContextMenu', row)
  msgList.value = msgList.value.map(item => {
    if (item.id === row.id) {
      item.contextMenuVisible = true
    } else {
      item.contextMenuVisible = false
    }
    return item
  })
}
</script>

<style lang="scss" scoped>
.content-container {
  flex-direction: row;
}
.base-table-container {
  display: flex;
  flex-direction: column;
}
.chat-items {
  flex: 1;
  overflow-y: auto;
  padding-bottom: 10px;
  .no-msg {
    text-align: center;
    font-size: 12px;
    color: #666;
  }
}
</style>
